package com.lyl.syt.service.impl;/**
 * @author Mr.Luo
 * @date 2022-04-24 15:09
 */

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyl.syt.dao.DictDao;
import com.lyl.syt.easyexcel.DictVoListener;
import com.lyl.syt.model.cmn.Dict;
import com.lyl.syt.service.DictService;
import com.lyl.syt.vo.cmn.DictEeVo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.Luo
 * @date 2022-04-24 15:09
 * @desc 医院设置service实现类
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictDao, Dict> implements DictService {

    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        List<Dict> dictList = lambdaQuery()
                .eq(Dict::getParentId, id)
                .list();

        dictList.forEach(t -> t.setHasChildren(isChildren(t.getId())));
        return dictList;
    }

    @Override
    public void exportExcel(HttpServletResponse response) {
        //导出设置
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        List<Dict> list = lambdaQuery().list();
        List<DictEeVo> voList = new ArrayList<>();
        list.forEach(t -> {
            DictEeVo vo = new DictEeVo();
            BeanUtil.copyProperties(t, vo);
            voList.add(vo);
        });

        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("dict")
                    .doWrite(voList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * allEntries = true: 方法调用后清空所有缓存
     * @param file
     */
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importExcel(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictVoListener(this))
                    .sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //根据dictcode和value查询名称
    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictcode为空，直接根据value查询
        if (StrUtil.isBlank(dictCode)){
            //根据value查询
            return lambdaQuery()
                    .eq(Dict::getValue, value)
                    .one()
                    .getName();
        }else {
            Dict parentDict = getByDictCode(dictCode);
            return lambdaQuery()
                    .eq(Dict::getParentId, parentDict.getId())
                    .eq(Dict::getValue, value)
                    .one()
                    .getName();
        }
    }

    private Dict getByDictCode(String dictCode) {
        return lambdaQuery().eq(Dict::getDictCode, dictCode).one();
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = getByDictCode(dictCode);
        return findChildData(dict.getId());
    }

    @Override
    public List<Dict> findByParentId(Long parentId) {
        return lambdaQuery()
                .eq(Dict::getParentId, parentId)
                .list();
    }

    /**
     * 判断是否存在子节点
     *
     * @param id id
     * @return boolean
     */
    private boolean isChildren(Long id) {
        return lambdaQuery()
                .eq(Dict::getParentId, id)
                .exists();
    }
}
